﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace EntityCreate
{
    public partial class Form1 : Form
    {
        private string CnnString = "";
        Database db = new Database();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            SaveFileDialog dlg = new SaveFileDialog();
            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                List<Table> dizi = gridControl1.DataSource as List<Table>;
                if (dizi != null)
                {
                    Tools.Serialize(dlg.FileName, dizi);
                }
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            CnnString = textBox1.Text;
            gridControl1.DataSource = db.GetSchema(CnnString);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                gridControl1.DataSource = Tools.DeSerialize(dlg.FileName);
            }
        }

        private string DbType(string type)
        {
            string aranan = type;
            if (aranan.IndexOf('(') > -1)
            {
                aranan = aranan.Substring(0, aranan.IndexOf('('));
            }

            string sonuc = "";
            switch (aranan.ToLower())
            {
                case "int":
                    sonuc = "int";
                    break;
                case "decimal":
                case "float":
                    sonuc = "decimal";
                    break;
                case "datetime":
                    sonuc = "DateTime";
                    break;

                case "varchar":
                case "nvarchar":
                    sonuc = "string";
                    break;
                case "image":
                    sonuc = "byte[]";
                    break;

                default:
                    sonuc = type;
                    break;
            }
            return sonuc;
        }

        private string EntityNameFind(string colNames, Table tbl)
        {
            string sonuc = "";
            foreach (var item in tbl.Columns)
            {
                if (colNames.IndexOf(item.Name) > -1)
                {
                    sonuc += "x." + item.EntityName + ",";
                }
            }
            if (sonuc.Length > 0)
            {
                sonuc = sonuc.Substring(0, sonuc.Length - 1);
            }
            return sonuc;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            List<Table> dizi = gridControl1.DataSource as List<Table>;
            if (dizi != null)
            {
                StringBuilder sb = new StringBuilder();
                foreach (var item in dizi)
                {
                    sb.AppendFormat("    public class {0}\r\n", item.EntityName);
                    sb.AppendLine("    {");
                    foreach (var col in item.Columns)
                    {
                        string colname = "";
                        if (!string.IsNullOrEmpty(col.EntityName))
                            colname = col.EntityName;
                        else
                            colname = col.Name;

                        sb.AppendFormat("        public {0} {1} ", DbType(col.DataType), colname);
                        sb.Append("{ get; set; }\r\n");
                    }
                    sb.AppendLine("    }");
                }

                //model
                sb.AppendLine("    public class PowerEntities : DbContext, IDisposable");
                sb.AppendLine("    {");
                foreach (var item in dizi)
                {
                    sb.AppendFormat("public DbSet<{0}> {1}", item.EntityName, item.EntityCogulAdi);
                    sb.AppendLine(" { get; set; }");

                }

                //mapping
                sb.AppendLine("        protected override void OnModelCreating(DbModelBuilder modelBuilder)");
                sb.AppendLine("    {");
                foreach (var item in dizi)
                {
                    sb.AppendFormat("            modelBuilder.Entity<{0}>().ToTable(\"{1}\");\r\n", item.EntityName, item.Name);
                    if (item.Columns[0].Identity)
                    {
                        sb.AppendFormat("            modelBuilder.Entity<{0}>().Property(x => x.{1}).HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.Identity);\r\n", item.EntityName, item.Columns[0].EntityName);
                    }
                    else
                    {
                        sb.AppendFormat("            modelBuilder.Entity<{0}>().Property(x => x.{1}).HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.None);\r\n", item.EntityName, item.Columns[0].EntityName);
                    }



                    foreach (var col in item.Columns)
                    {
                        sb.AppendFormat("            modelBuilder.Entity<{0}>().Property(c => c.{1}).HasColumnName(\"{2}\");\r\n", item.EntityName, col.EntityName, col.Name);
                    }

                    if (item.Indexes.Count > 0)
                    {
                        sb.AppendFormat("            modelBuilder.Entity<{0}>().HasKey(x => new ", item.EntityName);
                        sb.Append(" {");
                        foreach (var idx in item.Indexes)
                        {
                            if (idx.PrimaryKey)
                            {
                                sb.Append(EntityNameFind(idx.ColumnNames, item));
                            }
                        }
                        sb.Append(" });\r\n");
                    }


                }
                sb.AppendLine("    }");
                sb.AppendLine("    }");

                SaveFileDialog dlg = new SaveFileDialog();
                if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    File.WriteAllText(dlg.FileName, sb.ToString());
                }


            }
        }


    }
}
